package com.yzd.learnjava.concurrency;

import java.util.concurrent.TimeUnit;

import com.yzd.learnjava.util.Print;

public class InterruptingIdiom {
	public static void main(String[] args) throws InterruptedException {
		Thread t = new Thread(new Blocked3());
		t.start();
		TimeUnit.MILLISECONDS.sleep(10);
		t.interrupt();
	}
}

class NeedCeanup{
	private final int id ;
	public NeedCeanup(int ident) {
		this.id = ident;
		Print.print("NeedCleanup " + id);
	}
	
	public void cleanup() {
		Print.print("Cleaning up " + id);
	}
}

class Blocked3 implements Runnable{
	private volatile double d = 0.0;
	public void run() {
		try {
			while(!Thread.interrupted()) {
				NeedCeanup n1 = new NeedCeanup(1);
				try {
					Print.print("Sleeping");
					TimeUnit.MICROSECONDS.sleep(1);
					
					NeedCeanup n2 = new NeedCeanup(2);
					try {
						Print.print("Calculating");
						for(int i = 0 ; i < 2500000; i++) {
							d = d + (Math.PI + Math.E) / d;
						}
						Print.print("Finished time-consuming operation");
					}finally {
						n2.cleanup();
					}
				} finally {
					n1.cleanup();
				}
			}
			Print.print("Exiting via while() test");
		} catch (InterruptedException e) {
			Print.print("Exiting via while() InterruptedException");
			e.printStackTrace();
			
		}
	}
}